import crypto from "crypto";
import {getUploadToken} from "../../src/api/common";
import * as qiniu from "qiniu-js";
import BMF from 'browser-md5-file'; // 用于计算文件md5:https://www.npmjs.com/package/browser-md5-file

import {message} from "ant-design-vue";
const MAX_FILE_SIZE = 1 * 1024 * 1024; // 限制文件大小为 1MB
/**
 *七牛云上传单个文件
 * @param prefix 文件夹  xx/xx/xx/
 * @param file 文件
 * @param next 上传进度回调
 */
export function qinUpload(prefix,file,next) {

    return new Promise(async (resolve, reject) => {
        //校验文件大小
        if (file.size > MAX_FILE_SIZE) {
            message.info("文件超过允许的大小为1MB");
            reject("文件超过允许的大小限制!");
            return;
        }
        //获取上传token信息
        let res = null;
        try {
             res = await getUploadToken();
        } catch (e) {
            reject("token获取失败!");
            return;
        }

        const {token,url,region} = res.data;

        //生成文件md5
        let md5 = await computeFileMD5(file);

        //获取文件扩展名
        let extension = file.name.split('.').pop();

        //拼接最终上传路径
        const name = prefix + md5 + '.' + extension;

        //上传配置
        const config = {
            useCdnDomain: true,
            region: region
        };

        //开始上传
        const observable = qiniu.upload(file, name, token, config)

        //监听上传
        observable.subscribe(
            {
                next(res) {
                    // ...
                    if(next != undefined && next != null)
                        next(res)
                },
                error: (err) => {
                    // ...
                    reject(err)
                },
                complete: (res) => {
                    resolve(url + '/' + res.key)
                }
            }
        ) //

    })

}


// 计算文件的 MD5 值
function computeFileMD5(file) {
    // 对文件进行md5计算，节省云端存储空间
    const bmf = new BMF();
    return new Promise((resolve, reject) => {
        bmf.md5(
            file,
            (err, md5) => {
                if (err) {
                    reject(err);
                }
                resolve(md5);
            },
            (progress) => {
            //    console.log('progress number:', progress);
            },
        );
    });
}


